<?php

namespace app\controller\wmapi\examineapprove;

use app\controller\wmapi\IndexController;
use app\controller\wmapi\order\OrderController;
use app\model\WaChannel;
use app\model\WaSupplier;
use app\model\WaSupplierDomesticLogisticsFees;
use app\model\WaSupplierExamineApprove;
use app\model\WaSupplierExamineApproveFlow;
use app\model\WaSupplierFeeRelevance;
use app\model\WaSupplierInsuranceCompany;
use app\model\WaSupplierRegistrationFee;
use app\model\WaSupplierRegistrationFeeRelevance;
use app\model\WaSupplierTransferExportFee;
use app\model\WaSupplierTransferExportFeeRelevance;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;

class SupplierApproveController extends Validate
{

    /**
     * 供应商审批 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function supplierApproveList(Request $request)
    {
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取的是 销售审批id  因为记录不删 合同编号会存在重复
//        $purchasecontractsn = WaSupplierExamineApproveFlow::allIn($adminId);
//        $purchasecontractsn = json_decode($purchasecontractsn);
//        if (!$purchasecontractsn) {
//        }
        $purchasecontractsn = [];

        $fields = ['*'];
        $condition = [];
        $between = [];
        $whereNotIn = [3];
        if ($param['spf_no']) {
            $condition [] = ['spf_no', 'like', '%' . $param['spf_no'] . '%'];
        }

        if ($param['initiator_admin_name']) {
            $condition [] = ['initiator_admin_name', 'like', '%' . $param['initiator_admin_name'] . '%'];
        }
        $condition [] = ['status', '!=', 3];

        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaSupplierExamineApprove::list($page, $pageNum,$whereNotIn, $purchasecontractsn, $fields, $condition, $between);

        return IndexController::successed($rule, '供应商列表');
    }

    /**
     * 供应商审批-状态更新
     * @param Request $request
     * @return \support\Response
     */
    public function supplierApproveUpdate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
//        $condition []= ['spf_no', '=', $param['spf_no']];
        $adminId = json_decode(adminId($request));
        if (array_key_exists('refuse_reason',$param)){
            $refuse_reason = $param['refuse_reason'];
        }else{
            $refuse_reason = '';
        }

        // 当前供应商审批数据
        $approves = WaSupplierExamineApprove::find(['id' => $param['id']], $adminId);
        $approves = json_decode($approves);
        if (!$approves) {
            return IndexController::errored('', '找不到该供应商');
        }
        $flow = [];// 当前部门审批流
        $flow_next = []; // 下级部门审批流
        // 当前订单审批流
        $flows = WaSupplierExamineApprove::find(['id' => $param['id']], $adminId);
        $flows = json_decode($flows);
        if (!$flows) {
            return IndexController::errored('', '未获取供应商的审批流');
        }
        // 获取合同中的审批流设置
        $flows->approve_flow = json_decode($flows->approve_flow);

        $condition_flow = [];
        $condition_flow [] = ['spf_no', '=', $approves->spf_no];
        $condition_flow [] = ['status', '=', 0];
        $approve_flow = WaSupplierExamineApproveFlow::find($condition_flow);
        $approve_flow = json_decode($approve_flow);
        if (!$approve_flow) {
            return IndexController::errored('', '找不到该审批的待审批记录');
        }else{
            if (!in_array($adminId->id, json_decode($approve_flow->admin_ids))){
                return IndexController::errored('', '当前审批你没有审批权限');
            }

            foreach ($flows->approve_flow as $k) {
                //获取合同中该用户部门的 审批流
                if ($approve_flow->admin_ids ==  json_encode($k->approve_admin_id)) {
                    $flow = $k;
                }
            }

            if (!$flow) {
                return IndexController::errored('ErrorApproveSetting', '当前用户所在部门未设置审批流程，无法提交审批');
            }


        }

        \support\Db::beginTransaction();
        try {
            if ($param['status'] == 0) {
                return IndexController::errored('', '审批只有通过和驳回和撤回状态哦');
            } elseif ($param['status'] == 1) {
                // 审批通过 判断审批流是否走到最后一步 -> 如果是则多一步创建供应商   =》 都需要 添加供应商审批详情记录
                if ($approves) {
                    // 首先这合同必须是审批中的状态
                    if ($approves->status != 0) {
                        return IndexController::errored('', '订单不是待审批状态无法审批');
                    }
                    // 需要判断主订单是否是审批中的状态
                    if ($approves->approve_flow) {


//                    foreach (json_decode($approves->approve_flow) as $k){
                        // 然后判断 当前部门是否审批过 循环所有 审批流的所有部门 正常是按正序循环 找出上级部门为 0 的部门
                        //先查找是否有审批记录 按流程每一个审批操作会自动创建下一个 一条审批或待审批数据
                        $data = [];
                        $data [] = ['check_id', '=', $param['id']];
                        $data [] = ['status', '=', 0];
                        $check_parent = WaSupplierExamineApproveFlow::find($data);
                        $check_parent = json_encode($check_parent);
                        // 只有查到待审批数据的部门才有审批权限
                        if ($check_parent) {

                            // 添加供应商审批详情记录
                            $approve_log_data = [
                                'spf_no' => $approves->spf_no, // 供应商编号
                                'check_id' => $approves->id, // 审批id
                                'created_at' => dateTime(),
                                'admin_id' => $adminId->id,
                                'admin_ids' => json_encode($flow->approve_admin_id), //
                                'admin_name' => $adminId->nickname,
                                'refuse_reason' => $refuse_reason,
                                'status' => 1, //0 待审批 1审批通过 2 审批驳回
                            ];

                            $add_log = WaSupplierExamineApproveFlow::create($approve_log_data); // 添加供应商审批详情记录
                            if (!$add_log) {
                                return IndexController::errored('', '审批流添加错误');
                            }
                            // 判断审批流到哪一步 如果结束则 修改合同状态 创建合同
                            //判断是否是最后一级审批
                            if ($flow->next_sort == 0) {
                                // 最后一级审批  则修改合同审批状态  创建合同
                                // 由销售单创建的供应商 状态修改
                                if ($approves->supplier_id) {
                                    //修改供应商状态
                                    $supplier_up_data = [
                                        'approve_status' => 1,
                                        'updated_at' => dateTime()
                                    ];
                                    $supplier_status_up = IndexController::supplierStatusUpCommon($approves->supplier_type,$approves->supplier_id,$supplier_up_data);
                                    if (!$supplier_status_up != 'true'){
                                        \support\Db::rollBack();
                                        return IndexController::errored($supplier_status_up,'供应商状态修改失败');
                                    }

                                    // 手动创建的供应商
                                    $up_supplier_approve_status = WaSupplierExamineApprove::updated(['id' => $param['id']], ['status' => 1]); // 修改供应商审批单状态
                                    if (!$up_supplier_approve_status){
                                        \support\Db::rollBack();
                                        return IndexController::errored('','供应商审批状态修改失败');
                                    }
                                }else{
                                    return IndexController::errored('供应商状态修改失败id'.$approves->supplier_type, '供应商状态修改失败');
                                }



                            } else {
                                $next_sort = $flow->next_sort; //下一级部门
                                foreach ($flows->approve_flow as $k) {
                                    //获取合同中该用户部门的 审批流
                                    if ($k->sort == $next_sort) {
                                        $flow_next = $k;
                                    }

                                }
                                if ($flow_next) {
                                    // 创建下一级待审批流程
                                    $admin_name ='';
                                    if ($flow_next->approve_admin_id){
                                        foreach ($flow_next->approve_admin_id as $apadid) {
                                            $admins = WaAdmins::find(['id' => $apadid]);
                                            $admins = json_decode($admins);
                                            if ($admins) {
                                                $admin_name = $admin_name .'/'. $admins->nickname;
                                            }
                                        }

                                    }
                                    // 添加供应商审批详情记录
                                    $approve_log_data = [
                                        'spf_no' => $approves->spf_no, // 供应商编号
                                        'check_id' => $approves->id, // 审批id
                                        'created_at' => dateTime(),
                                        'admin_id' => $adminId->id,
                                        'admin_ids' => json_encode($flow_next->approve_admin_id), //
                                        'admin_name' => $admin_name,
                                        'status' => 0, //0 待审批 1审批通过 2 审批驳回
                                    ];

                                    $add_log = WaSupplierExamineApproveFlow::create($approve_log_data); // 添加供应商审批详情记录
                                    if (!$add_log) {
                                        return IndexController::errored('', '审批流日志添加失败');
                                    }
                                }

                            }

                        } else {
                            return IndexController::errored('', '不满足操作条件,请查看合同审批状态 和 审批权限');
                        }
//                    }
                    }
                }

            } elseif ($param['status'] == 2) {


                // 审批驳回 修改：供应商状态为 审批驳回 添加审批驳回的理由两边都要 添加供应商审批详情记录
                // 审批驳回驳回后是创建新的审批流  旧的失败记录保留
                // 手动创建的供应商
                $up_purchase_approve_status = WaSupplierExamineApprove::updated(['id' => $param['id']], ['status' => 2, 'refuse_reason' => $param['refuse_reason'], 'updated_at' => dateTime()]); // 修改供应商审批单状态
                // 添加供应商审批详情记录
                $approve_log_data = [
                    'spf_no' => $approves->spf_no, // 供应商编号
                    'check_id' => $approves->id, // 审批id
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_ids' => json_encode($flow->approve_admin_id), //
                    'admin_name' => $adminId->nickname,
                    'refuse_reason' => $refuse_reason,
                    'status' => 2, //0 待审批 1审批通过 2 审批驳回 3作废 4  删除
                ];

                $approve_log_data['refuse_reason'] = $param['refuse_reason'];
                $add_log = WaSupplierExamineApproveFlow::create($approve_log_data); // 添加供应商审批详情记录
                if (!$add_log) {
                    return IndexController::errored('', '审批流日志添加失败');
                }
                //供应商状态
                // 供应商类型： 1车辆供应商 2上牌供应商 3 国际货运代理 4保险供应商 5 国内物流
                // 0 正常 1 禁用 4 删除
                // 审批状态 0 待审批 1 审批通过 2 审批驳回
                $supplier_up_data = [
                    'approve_status' => 2,
                    'updated_at' => dateTime()
                ];
                $supplier_status_up = IndexController::supplierStatusUpCommon($approves->supplier_type,$approves->supplier_id,$supplier_up_data);
                if (!$supplier_status_up != 'true'){
                    \support\Db::rollBack();
                    return IndexController::errored($supplier_status_up,'供应商状态修改失败');
                }
            } elseif ($param['status'] == 3) {
                // 撤回 -> 整个合同和审批都撤回 并添加操作记录
                return IndexController::errored('', '撤回是供应商页面操作,这边是审批只添加撤回记录，不做实际操作');
            } else {
                return IndexController::errored('', '供应商审批状态没有此状态');
            }

            \support\Db::commit();
            return IndexController::successed('', '供应商审批状态修改成功');
        } catch (\Throwable $exception) {

            IndexController::logError('supplierApproveUpdate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '供应商审批状态修改失败');
        }

    }

    /**
     * 供应商审批-详情
     * @param Request $request
     * @return \support\Response
     */
    public function supplierApproveDetail(Request $request)
    {

//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $where_condition = [];
        $where_condition [] = ['status', '!=', 3];
        $where_condition [] = ['spf_no', '=', $param['spf_no']];
        $supplier_approve = WaSupplierExamineApprove::find($where_condition,$adminId);
        $supplier_approve = json_decode($supplier_approve);
        // 获取审批数据 审批
        if ($supplier_approve) {
            $supplier_approve->approve_flow = json_decode($supplier_approve->approve_flow);
            foreach ($supplier_approve->approve_flow as $kapprove) {
                $admin_name ='';
                if ($kapprove->approve_admin_id){
                    foreach ($kapprove->approve_admin_id as $apadid) {
                        $admins = WaAdmins::find(['id' => $apadid]);
                        $admins = json_decode($admins);
                        if ($admins) {
                            $admin_name = $admin_name .'/'. $admins->nickname;
                        }
                    }

                }

                $kapprove->check_time = '';
                $kapprove->refuse_reason = '';
                $kapprove->status = 0;
                $kapprove->status_name = '待审批';
                $kapprove->admin_name = $admin_name;
            }
            // 销售单审批状态  0 待审核 1 审批通过 2 审批驳回  3 作废 4  删除
            if ($supplier_approve->status == 0) {
                $supplier_approve->status_name = '待审核';
            } elseif ($supplier_approve->status == 1) {
                $supplier_approve->status_name = '审批通过';
            } elseif ($supplier_approve->status == 2) {
                $supplier_approve->status_name = '审批驳回';
            } elseif ($supplier_approve->status == 3) {
                $supplier_approve->status_name = '已撤回';
            } elseif ($supplier_approve->status == 4) {
                $supplier_approve->status_name = '删除';
            } else {
                $supplier_approve->status_name = '';
            }
            // 审批进度
            if ($supplier_approve->id) {

//                $supplier_approve_flow = WaSupplierExamineApproveFlow::all(['check_id' => $supplier_approve->id]);
                $supplier_approve_flow = WaSupplierExamineApproveFlow::all(['spf_no' => $supplier_approve->spf_no]);
                $supplier_approve_flow = json_decode($supplier_approve_flow);
                if ($supplier_approve_flow) {
                    foreach ($supplier_approve_flow as $approve) {

                        // 状态
                        if (intval($approve->status) == 0) {
                            $approve->status_name = '审批中';
                        } elseif ($approve->status == 1) {
                            $approve->status_name = '审批通过';

                            if ($supplier_approve->approve_flow) {
                                foreach ($supplier_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)   && $approve->status == 1){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }

                        } elseif ($approve->status == 2) {
                            $approve->status_name = '审批驳回';

                            if ($supplier_approve->approve_flow) {
                                foreach ($supplier_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 2){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }

                        } elseif ($approve->status == 3) {
                            $approve->status_name = '已撤回';

                            if ($supplier_approve->approve_flow) {
                                foreach ($supplier_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 3){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;

                                    }
                                }
                            }
                        } else {
                            $approve->status_name = '';
                        }



                    }
                    $supplier_approve->initiator = $supplier_approve_flow[0];
                }
                $supplier_approve->purchase_approve_flow = $supplier_approve_flow;
            } else {
                $supplier_approve->purchase_approve_flow = [];
                $supplier_approve->initiator = '';
            }

        } else {
            return IndexController::errored('', '获取销售审批数据失败');
        }

        return IndexController::successed(json_encode($supplier_approve), '');
    }

}